package com.shelpe.services.sustainer.autoDrive;

import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.sustainer.client.SimbaSyncClient;
import com.shelpe.services.sustainer.entity.jpa.AutoProductQueue;
import com.shelpe.services.sustainer.repository.jpa.AutoProductQueueRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class MobileQscoreSyncProcessor implements ItemProcessor<AutoProductQueueInput, AutoProductQueueResult> {

	@Autowired
	private SimbaSyncClient simbaSyncClient;
	@Autowired
	private AutoProductQueueRepository autoProductQueueRepository;
	
	@Override
	public AutoProductQueueResult process(AutoProductQueueInput input) throws Exception {
		AutoProductQueue.QueuePK pk = input.getPk();
		AutoProductQueue item = this.autoProductQueueRepository.findOne(pk);
		log.debug("StartSyncMobileQscore[{}]:{}", pk.getCampaignID(), item);
		AutoProductQueueResult res = new AutoProductQueueResult();
		res.setQueue(item);
		res.setCampaignID(pk.getCampaignID());
		res.setChunk(input.getChunk());
		if(item != null){
			if(item.getStatus() == AutoProductQueue.Status.success && item.getAdgroupID() > 0 && item.getFlag() == 1){
				SimbaSyncClient.SyncResultDto dto = this.simbaSyncClient.syncMobileQscore(item.getUserID(), item.getAdgroupID());
				if(dto.getUpdateNum() == 0){
					log.error("fail to sync mobile qscore: {} {}", pk, dto);
				}
				res.setStatus(ResultStatus.success);
			}else{
				res.setStatus(ResultStatus.invalidStatus);
			}
		}else{
			res.setStatus(ResultStatus.notFound);
		}
		return res;
	}

}
